import React, { useState } from 'react'
import ReactDOM from 'react-dom'
import { ConfigProvider, Button, Modal, Input, toast } from '@ones-design/core'
import { lifecycle, OPProvider } from '@ones-op/bridge'
import { useUserInfo } from '@ones-op/store'
import { OPFetch } from '@ones-op/fetch'

import './index.css'

const fetchProject = OPFetch.create({ baseURL: '/project/api/project' })

const AppPage: React.FC = () => {
  const userInfo = useUserInfo()
  const [modalVisible, setModalVisible] = useState(false)
  const [content, setContent] = useState('')
  function handlerClick() {
    setModalVisible(true)
  }

  async function saveContent(content: string) {
    const url = `/notice/addData`
    await fetchProject({
      url,
      method: 'POST',
      data: {
        content,
      },
      headers: {
        // 注意这里，如果接口是组织类型的，就是用 organization，如果是团队类型的，就是用 team
        'ones-check-point': 'organization',
      },
    })
  }

  return (
    <>
      <div className="btnContainer">
        <Button onClick={handlerClick}>Hello World</Button>
      </div>

      <Modal
        visible={modalVisible}
        title="Modal 对话框"
        onCancel={() => {
          setModalVisible(false)
        }}
        onOk={async () => {
          console.log(content)
          const res = await saveContent(content)
          toast.success('保存成功')
          setModalVisible(false)
        }}
      >
        <div>
          <div style={{ marginBottom: 20 }}>hello {userInfo?.name}</div>
          <Input.TextArea
            onChange={(e) => {
              setContent(e.target.value)
            }}
            placeholder="请输入自定义文本"
          />
        </div>
      </Modal>
    </>
  )
}

ReactDOM.render(
  <ConfigProvider>
    <OPProvider>
      <AppPage />
    </OPProvider>
  </ConfigProvider>,
  document.getElementById('ones-mf-root')
)

lifecycle.onDestroy(() => {
  ReactDOM.unmountComponentAtNode(document.getElementById('ones-mf-root'))
})
